package com.cold.demo.template.test;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import org.springframework.util.StreamUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class Ts2Mp4 {
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(32);

        Map<String, String> header = new HashMap<>();
        header.put("Referer", "");
        header.put("sec-ch-ua", "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"");
        header.put("sec-ch-ua-mobile", "?0");
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36");

        String getTsUrl = "https://vod3.bdzybf3.com/20201224/Z7OoARE2/1000kb/hls/index.m3u8";
        HttpRequest get = HttpUtil.createGet(getTsUrl);
        get.headerMap(header, true);
        String body = get.execute().body();
        List<String> tsUrls = Arrays.asList(body.split("\n")).stream()
                .filter(s -> s.startsWith("http"))
                .collect(Collectors.toList());

        List<Future<InputStream>> list = new ArrayList<>();
        for (String tsUrl : tsUrls) {
            Future<InputStream> submit = executorService.submit(() -> {
                try {
                    System.out.println("开始下载：" + tsUrl);
                    HttpRequest tsGet = HttpUtil.createGet(tsUrl);
                    tsGet.timeout(60 * 1000);
                    tsGet.headerMap(header, true);
                    return tsGet.execute().bodyStream();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("异常：" + tsUrl);
                } finally {
                    System.out.println("执行完毕：" + tsUrl);
                }
                return null;
            });
            list.add(submit);
        }

        AtomicInteger b = new AtomicInteger();
        list.forEach(s -> {
            try {
                InputStream inputStream = s.get();
                FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Downloads\\202103101615364653111662\\"+b.get()+".ts");
                StreamUtils.copy(inputStream, fos);
                fos.close();
                inputStream.close();
                System.out.println("成功："+b.incrementAndGet());
            } catch (InterruptedException | ExecutionException | IOException e) {
                e.printStackTrace();
            }
        });

        executorService.shutdown();
        System.out.println("ok");
    }
}
